package ActiveMQ.pb;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by brossdong on 2017/12/16.
 */
public class Consumer1 {
    //连接工厂
    private ConnectionFactory connectionFactory;

    //连接对象
    private Connection connection;

    //session对象
    private Session session;

    //消费者
    private MessageConsumer messageConsumer;

    //目标地址
    Destination destination;

    public Consumer1() {
        try {
            this.connectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnectionFactory.DEFAULT_USER,
                    ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                    "tcp://localhost:61616");
            this.connection = this.connectionFactory.createConnection();
            this.connection.start();
            this.session = this.connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
            this.destination = this.session.createQueue("first");

            this.messageConsumer = this.session.createConsumer(this.destination);
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void receiver() throws Exception {
        Destination destination = session.createTopic("topic1");
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(new Listener());
    }
    class Listener implements MessageListener{
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {

                }

                if (message instanceof MapMessage) {
                    TextMessage ret = (TextMessage) message;
                    System.out.println(ret.getText());
                    /*System.out.println(ret.getString("name"));
                    System.out.println(ret.getString("age"));*/
                }
            }catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        Consumer1 c = new Consumer1();
        try {
            c.receiver();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
